<template>
    <UnitBaseInfo :opType="opType" :opUnitInfo="opUnitInfo" v-if="(opType==1||opType==3)&&opUnitInfo.id"/>

    <el-card class="w-full mt-[10px]">
      <CardHead> 年度记录 </CardHead>

      <el-table v-loading="loading" :data="annalsList">
        <el-table-column label="年度" align="center" prop="yearOnly" width="120"/>
        <el-table-column label="年报附件" align="center" prop="fileIds">
          <template #default="scope">
            <div v-if="scope.row.fileIds" >
              <div v-for="(item, index) in scope.row.fileIds.split(',')" :key = index>
                <el-link type="primary" @click.prevent="download.resource(item)">{{item.split(/[\/\\]+/).pop()}}</el-link>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="上传时间" align="center" prop="uploadDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.uploadDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="note" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="opType==1&&opUnitInfo.id">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['research:annals:edit']">编辑</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['research:annals:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0&&false"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <el-form ref="annalsRef" :model="form" :rules="rules" label-width="96px" v-if="opType==1&&opUnitInfo.id">
      <el-card class="w-full mt-[10px]">
        <CardHead> {{title}} </CardHead>

        <el-row :gutter="20">
            <el-col :span="1"></el-col>
            <el-col :span="6">
              <el-form-item label="年度" prop="yearOnly">
                <el-select v-model="form.yearOnly" placeholder="请选择年度">
                  <el-option
                    v-for="dict in yearOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="上传时间" prop="uploadDate">
                <el-date-picker clearable
                  v-model="form.uploadDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择上传时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="年报附件" prop="fileIds">
                <file-upload v-model="form.fileIds" :limit=1 :fileSize=20 :fileType="['doc','docx','xls','xlsx','pdf']" :isShowTip="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="1"></el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="1"></el-col>
            <el-col :span="22">
              <el-form-item label="备注" prop="note">
                <el-input v-model="form.note" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="1"></el-col>
        </el-row>
      </el-card>
    </el-form>
</template>

<script setup name="Annals">
import cloneDeep from 'lodash/cloneDeep';  
import useUserStore from '@/store/modules/user';
import CardHead from "./CardHead.vue";
import UnitBaseInfo from "./UnitBaseInfo.vue";
import { getOverPastYearOptions } from "@/api/research/unit";
import { listAnnals, getAnnals, delAnnals, addAnnals, updateAnnals } from "@/api/research/annals";
import download from '@/plugins/download'

const { proxy } = getCurrentInstance();

const emit = defineEmits(['refreshUnitList']);  
const props = defineProps({
  opType: {  
    type: Number,
    required: true,
    default: 0      // 默认值  0:add 1:edit 2:check 3:view
  },
  opUnitInfo: {  
    type: Object,
    required: false,
  }
}) 

const annalsList = ref([]);
const loading = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const yearOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
    researchUnitId: props.opUnitInfo.id,
  },
  rules: {
    yearOnly: [
      { required: true, message: "年度不能为空", trigger: "change" }
    ],
    uploadDate: [
      { required: true, message: "上传时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

onMounted(() => {
  yearOptions.value = getOverPastYearOptions(5,true);
  handleAdd()
})

function getList() {
  loading.value = true;
  listAnnals(queryParams.value).then(response => {
    annalsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function reset() {
  form.value = {
    id: null,
    researchUnitId: props.opUnitInfo.id,
    yearOnly: null,
    uploadDate: null,
    fileIds: null,
    note: null,
    CREATEUSERID: null,
    LASTEDITUSERID: null,
    CREATEDATE: null,
    LASTEDITDATE: null,
    CREATEUSERNAME: null,
    LASTEDITUSERNAME: null
  };
  proxy.resetForm("annalsRef");
}

function handleAdd() {
  reset();
  title.value = "平台年报新增";
}

function handleUpdate(row) {
  reset();
  const _ID = row.id || ids.value
  getAnnals(_ID).then(response => {
    form.value = response.data;
    title.value = "平台年报编辑";
  });
}

function handleDelete(row) {
  const _IDs = row.id || ids.value;
  proxy.$modal.confirm('您确定要删除吗?').then(function() {
    return delAnnals(_IDs);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
    handleAdd();
  }).catch(() => {});
}

function save() {
  proxy.$refs["annalsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateAnnals(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          getList();
          handleAdd();
          // proxy.$modal.confirm('是否继续操作？').then(function() {
          //     handleAdd();
          // }).catch(() => {
          //     cancel();
          //     emit('refreshUnitList');
          // });
        });
      } else {
        addAnnals(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          getList();
          handleAdd();
          // proxy.$modal.confirm('是否继续操作？').then(function() {
          //     handleAdd();
          // }).catch(() => {
          //     cancel();
          //     emit('refreshUnitList');
          // });
        });
      }
    }
  });
}

function cancel() {
  reset();
}

defineExpose({save,cancel});
getList();
</script>

<style scoped lang="scss">
@import url("../index.scss");
</style>